package com.bw.controller;

import com.bw.common.Md5Utils;
import com.bw.common.TokenUtils;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class LoginController {

    @Autowired
    UserMapper  userMapper;

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/loginPage.do")
    public String loginPage(){
        return "login";
    }

    /**
     * 执行登录
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletResponse response){

        if (result.hasErrors()){
            // 获取校验结果中的 随机一个异常信息
            String defaultMessage = result.getAllErrors().get(0).getDefaultMessage();
            // 把异常信息返回给页面
            model.addAttribute("error",defaultMessage);
            return "login";
        }

        // 用户名是否存在
        User userFromDB = userMapper.selectByName(loginUser.getName());

        if (userFromDB == null){
            model.addAttribute("error","用户名不存在");
            return "login";
        }
        //校验密码
        String pwd = loginUser.getPwd();

        String salt = userFromDB.getSalt();

        String dBPwd = userFromDB.getPwd();

        // 加密 用户输入的密码 和数据库里的盐
        String md5String = Md5Utils.getMD5String(pwd + salt);

        if (! md5String.equals(dBPwd)){
            model.addAttribute("error","密码错误");
            return "login";
        }
        // 加密用户对象， 得到令牌token   把token放入cookie  通过response 返回给浏览器
        TokenUtils.responseTokenByCookie(userFromDB,response);

        return "redirect:list.do";
    }

    /**
     * 成功页面
     * @return
     */
    @RequestMapping("/success.do")
    public String success(HttpServletRequest request, Model model){
        // 展示 用户的昵称 和头像
        // 从request 中获取cookie  ，从cookie中获取令牌， 再解析出令牌 得到当前登录用户
        User loginUser = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("nickName",loginUser.getNickName());
        model.addAttribute("avatarUrl",loginUser.getAvatarUrl());
        return "success";
    }
}
